<?php
function download_chong_emails($pass) {
	$gmails = get_gmails();
	if($gmails){
		$name = str_replace('.', '', substr($gmails[0], 0, strpos($gmails[0], '@')));
		header('Content-type: text/txt');
		$file = $name . '.txt';
		header('Content-Disposition: attachment; filename="'.$file.'"');
		foreach ($gmails as $gmail) {
			echo "$gmail	$gmail	$pass	pop.gmail.com	995	1\r\n";
		}
	}
}

function get_gmails(){
	$gmail = trim($_POST['gmail']);
	$gmails = array();
	if(preg_match('/^([\w\.\-]+)(@gmail.com)?$/i', $gmail, $r)){
		$gmail = $r[1];
		$gmail = strtolower(str_replace('.', '', $gmail));
		$chars = str_split($gmail);
		
		$one = $_POST['one'];
		$two = $_POST['two'];
		$three = $_POST['three'];
		$all = $_POST['all'];
		
//		echo $gmail . PHP_EOL;
		$len = count($chars);
		$r = array();
		$r = get_strs($chars, 0);
		usort($r, 'sort_gmails');
		
		if($all || !$one && !$two && !$three){
			foreach ($r as $e) {
				$gmails[] = $e . '@gmail.com';
//				echo $e . '@gmail.com' . PHP_EOL;
			}
		}else{
			foreach ($r as $e) {
				$n = substr_count($e, '.');
				if($one && $n == 1 || $two && $n == 2  || $three && $n == 3)
					$gmails[] = $e . '@gmail.com';
//					echo $e . '@gmail.com' . PHP_EOL;
			}
		}
	}
	return $gmails;
}

function render_gmails(){
	$gmails = get_gmails();
	foreach ($gmails as $gmail) {
		echo $gmail . PHP_EOL;
	}
}

function sort_gmails($g1, $g2){
	$n1 = substr_count($g1, '.');
	$n2 = substr_count($g2, '.');
	if($n1 == $n2)
		return strcmp($g1, $g2);
	return $n1 > $n2;
}

function get_strs($chars, $start){
	if($start >= count($chars))
		return null;
	if($start == count($chars) - 1)
		return array($chars[$start]);
	$c = $chars[$start];
	$strs = get_strs($chars, $start+1);
	if($strs){
		$n = count($strs);
		$r = array();
		foreach ($strs as $str) {
			$r[] = $c . $str;
		}
		foreach ($strs as $str) {
			$r[] = $c . '.' . $str;
		}
	}
	return $r;
}